import { useIntervalFn, watchOnce } from '@peng_kai/kit/libs/vueuse';
import { getCookieValue, setCookie } from '~/utils';
import { jsBridge } from '~/utils/defines';

export function useMeta() {
  const _localSource = sessionStorage.getItem('SOURCE');
  if (_localSource && window.source)
    return _localSource;
  const searchParams = new URLSearchParams(location.search);
  const source = searchParams.get('source') || _localSource || getCookieValue('SOURCE') || '';
  sessionStorage.setItem('SOURCE', source);
  window.source = source;
  jsBridge.cid = source;
  // 请求manifest.json文件
  const manifestHref = '/manifest.json';
  const linkElement = document.createElement('link');
  linkElement.rel = 'manifest';
  if (source) {
    linkElement.href = `${manifestHref}?source=${source}`;
  }
  else {
    linkElement.href = manifestHref;
  }
  document.head.appendChild(linkElement);
  const idState = ref(false);
  const { pause } = useIntervalFn(() => {
    if (window.posPlatform) {
      if (window.posPlatform === 1 && window.posId) {
        insertMetaPixel(window.posId);
        saveSourceToCookie(source);
      }
      if (window.posPlatform === 7) {
        kuaishouPlatform(source);
      }
      if (window.posPlatform === 6) { // TG
        saveSourceToCookie(source);
      }
      idState.value = true;
    }
  }, 200);

  watchOnce(idState, () => pause());

  return source;
}

function insertMetaPixel(pixelId: string) {
  // const pixelId = '1681423272635523';
  // 创建并插入脚本元素
  const script = document.createElement('script');
  script.innerHTML = `
    !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', '${pixelId}');
  `;
  document.head.appendChild(script);

  // 创建并插入 noscript 元素
  const noscript = document.createElement('noscript');
  noscript.innerHTML = `
    <img height="1" width="1" style="display:none"
      src="https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1"
    />
  `;
  document.body.appendChild(noscript);
  noticeMeta().viewPage();
}

function kuaishouPlatform(source: string) {
  saveSourceToCookie(source);
}

function saveSourceToCookie(source: string) {
  setCookie('SOURCE', source);
}
interface IRegisterParams {
  plateform: string;
  id: string;
}

interface IPayParams {
  currency: string;
  value: number;
}
class MetaBase {
  viewPage(): void {};
  register(params: IRegisterParams): void {};
  deposit(params: IPayParams): void {};
  withdraw(params: IPayParams): void {};
}

class FaceBook extends MetaBase {
  viewPage(): void {
    console.log('触发浏览界面');
    window.fbq('track', 'PageView');
  }

  register(params: IRegisterParams): void {
    console.log('触发注册', params);
    // window?.fbq('track', 'CompleteRegistration', params);
  }

  deposit(params: IPayParams): void {
    console.log('触发充值', params);
    // window.fbq('track', 'Purchase', params);
  }

  withdraw(params: IPayParams): void {
    // window.fbq('trackCustom', 'withdraw', params);
  }
}

export function noticeMeta() {
  if (window.adObj)
    return window.adObj;
  let notice: MetaBase | undefined;
  if (window.posPlatform === 1) {
    notice = new FaceBook();
  }
  if (notice)
    window.adObj = notice;
  return notice || new MetaBase();
}

interface Data {
  id: number;
  [key: string]: any;
}
